package com.kgc.server.controller;

import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.kgc.server.pojo.Address;
import com.kgc.server.pojo.Page;
import com.kgc.server.pojo.User;
import com.kgc.server.service.UserService;
import com.kgc.server.util.ResponseMessage;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class UserController {
    Logger logger = Logger.getLogger(getClass());
    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @RequestMapping("getRegular")
    @ResponseBody
    @CrossOrigin
    public List getRegular(){
        return userService.getRegular();
    }

    @RequestMapping("getUserList")
    @ResponseBody
    @CrossOrigin
    public List getUserList(){
        return userService.getUserList();
    }

    @RequestMapping(value = "/captcha", produces = "image/jpeg")
    @ResponseBody
    @CrossOrigin
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        // 定义response输出类型为image/jpeg
        response.setDateHeader("Expires", 0);
        // 设置http标准
        response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
        // 设置请求头
        response.addHeader("Cache-Control", "post-check=0,pre-check=0");
        response.setHeader("Pragma", "no-cache");
        // 响应返回的是image/jpeg类型
        response.setContentType("image/jpeg");
        /*--------------生成验证码-------------*/
        String text = defaultKaptcha.createText();  // 获取验证码文本内容
        System.out.println("验证码为" + text);
        //验证码放到redis中
        redisTemplate.opsForValue().set("yzm",text);
        // 将验证码文本内容放入session
        request.getSession().setAttribute("captcha", text);
        // 根据文本验证码内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            // 输出流输出文件格式为jpg
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("login")
    @ResponseBody
    @CrossOrigin
    public boolean login(HttpServletRequest request, @RequestParam("code") String code) {
        String sessionCode = (String)redisTemplate.opsForValue().get("yzm");
        if (code.equals(sessionCode)) {
            return true;
        } else {
            return false;
        }
    }

    @RequestMapping("setUser")
    @ResponseBody
    @CrossOrigin
    public boolean setUser(User user){
        logger.info("setUser user:"+user);
        int num = userService.setUserList(user);
        logger.info("setUser user:"+user+",num:"+num);
        if( num > 0 ){
            return true;
        }
        return false;
    }

    @RequestMapping("UploginStatus")
    @ResponseBody
    @CrossOrigin
    public ResponseMessage UploginStatus(String userName) {
        logger.info("UserServiceImp  UploginStatus  userName:"+userName);
        ResponseMessage msg = new ResponseMessage();
        if (redisTemplate.hasKey(userName)){
            //有则重新设置时间
            redisTemplate.expire(userName,30, TimeUnit.MINUTES);
            msg.setMsg("续登成功");
            msg.setCode("200");
        }else {
            //没有则返回数据将返回并删除登录信息
            msg.setCode("500");
            msg.setMsg("登录已经失效");
        }
        logger.debug("userLogin param msg:"+msg);
        return msg;
    }

//    public ResponseMessage loginStatus(String userName) {
//        logger.info("UserServiceImpl loginStatus userName:"+userName);
//        ResponseMessage msg = new ResponseMessage();
//        if (null==userName){
//            msg.setCode("500");
//            msg.setMsg("用户登录信息已过期，请重新登录");
//            return msg;
//        }
//        if (redisTemplate.hasKey(userName)){
//            //如果存在 取出用户信息
//            User user = (User)getUserListByID(String.valueOf(id)).getData();
//            msg.setCode("200");
//            msg.setData(user);
//        }else {
//            msg.setCode("500");
//            msg.setMsg("用户登录信息已过期，请重新登录");
//        }
//        logger.debug("userLogin param msg:"+msg);
//        return msg;
//    }

    @RequestMapping("getRedisUserInfoList")
    @ResponseBody
    @CrossOrigin
    public User getRedisUserInfoList(User user){
        logger.info("getRedisUserInfoList user:"+user);
        User user1 = userService.getRedisUserInfoList(user);
        logger.info("getRedisUserInfoList user:"+user+",user1:"+user1);
        return user1;
    }

    @RequestMapping("getUserListFy")
    @ResponseBody
    @CrossOrigin
    public List getUserListFy(Page page, String username){
        logger.info("getUserListFy page:"+page+",username:"+username);
        page.setUsername(username);
        List list = userService.getUserListFy(page);
        list.add(page);
        logger.info("getUserListFy page:"+page+",username:"+username+",list:"+list);
        return list;
    }

    @RequestMapping("delUserListById")
    @ResponseBody
    @CrossOrigin
    public boolean delUserListById(int id){
        logger.info("delUserListById id:"+id);
        int num = userService.delUserListById(id);
        logger.info("delUserListById id:"+id+",num:"+num);
        if( num > 0 ){
            return true;
        }
        return false;
    }

    @RequestMapping("getUserListByID")
    @ResponseBody
    @CrossOrigin
    public List getUserListByID(int id){
        logger.info("getUserListByID id:"+id);
        List list = userService.getUserListByID(id);
        logger.info("getUserListByID id:"+id+",list:"+list);
        return list;
    }

    @RequestMapping("updateUserListByID")
    @ResponseBody
    @CrossOrigin
    public boolean updateUserListByID(User user){
        logger.info("updateUserListByID user:"+user);
        int num = userService.updateUserListByID(user);
        logger.info("updateUserListByID user:"+user+",num:"+num);
        if( num > 0 ){
            return true;
        }
        return false;
    }

    @RequestMapping("delRedisByUserName")
    @ResponseBody
    @CrossOrigin
    public boolean delRedisByUserName(String userName){
        logger.info("delRedisByUserName userName:"+userName);
        boolean flag = redisTemplate.delete(userName);
        logger.info("delRedisByUserName userName:"+userName+",flag:"+flag);
        if( flag == true ){
            return true;
        }
        return false;
    }

    @RequestMapping("setAddressById")
    @ResponseBody
    @CrossOrigin
    public boolean setAddressById(Address address){
        logger.info("setAddressById address:"+address);
        int num = userService.setAddressById(address);
        logger.info("setAddressById address:"+address+",num:"+num);
        if( num > 0 ){
            return true;
        }
        return false;
    }

    @RequestMapping("getAddress")
    @ResponseBody
    @CrossOrigin
    public List getAddress(int userId){
        logger.info("getAddress userId:"+userId);
        List list = userService.getAddress(userId);
        logger.info("getAddress userId:"+userId+",list:"+list);
        return list;
    }

    @RequestMapping("getAddressById")
    @ResponseBody
    @CrossOrigin
    public List getAddressById(int id){
        logger.info("getAddressById id:"+id);
        List list = userService.getAddressById(id);
        logger.info("getAddressById id:"+id+",list:"+list);
        return list;
    }

    @RequestMapping("updataAddressById")
    @ResponseBody
    @CrossOrigin
    public int updataAddressById(Address address){
        logger.info("updataAddressById address:"+address);
        int num = userService.updataAddressById(address);
        logger.info("updataAddressById address:"+address+",num:"+num);
        return num;
    }

    @RequestMapping("updataMrAddress")
    @ResponseBody
    @CrossOrigin
    public int updataMrAddress(int id,int userId){
        logger.info("updataMrAddress id:"+id+",userId:"+userId);
        int num1 = userService.updataAll(userId);
        int num = userService.updataMrAddress(id);
        logger.info("updataMrAddress id:"+id+",userId:"+userId+",num:"+num+",num1:"+num1);
        return num;
    }

    @RequestMapping("delAddressById")
    @ResponseBody
    @CrossOrigin
    public int delAddressById(int id){
        logger.info("delAddressById id:"+id);
        int num = userService.delAddressById(id);
        logger.info("delAddressById id:"+id+",num:"+num);
        return num;
    }

    @RequestMapping("setUserPassWordById")
    @ResponseBody
    @CrossOrigin
    public boolean setUserPassWordById(String email,String password,String userName){
        logger.info("setUserPassWordById email:"+email+",password:"+password);
        int num = userService.setUserPassWordById(email,password,userName);
        logger.info("setUserPassWordById id:"+email+",password:"+password+",num:"+num);
        if( num > 0 ){
            return true;
        }
        return false;
    }

}
